from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage, InvalidPage

from utils import flickrapi as f_api
from garetjax import config
from models import Photo

import flickrapi

def auth_callback(request):
    f = flickrapi.FlickrAPI(config.get('flickr:api_key'),
                            config.get('flickr:api_secret'))

    frob = request.GET['frob']
    token = f.get_token(frob)
    config.set('flickr:token', token)

    return HttpResponseRedirect('/fotografie/sync')

def list_photos(request, page_num=None, **kwargs):
    photos = Paginator(Photo.objects.all(), int(config.get('flickr.photos_per_page', 15)))
    
    if page_num is None:
        try:
            page_num = int(request.GET.get('page', '1'))
        except ValueError:
            page_num = 1
    else:
        try:
            page_num = int(page_num)
        except ValueError:
            page_num = 1
    
    try:
        page = photos.page(page_num)
    except (EmptyPage, InvalidPage):
        page = photos.page(photos.num_pages)
    
    return render_to_response('flickr/list_photos.html', {
        'photos': page
    }, RequestContext(request))
    
def single(request, photo_id):
    return render_to_response('flickr/single.html', {
        'p': get_object_or_404(Photo, id=photo_id),
    }, RequestContext(request))